﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace CNative.DbUtils
{
    /// <summary>
    /// 数据库所有表的信息
    /// </summary>
    public class DbTableInfo
    {
        /// <summary>
        /// 表名
        /// </summary>
        public string TableName { get; set; }

        /// <summary>
        /// 库名
        /// </summary>
        public string Schema { get; set; }

        /// <summary>
        /// 表描述说明
        /// </summary>
        public string Description
        {
            get
            {
                return _description.IsNullOrEmpty() ? TableName : _description;
            }
            set
            {
                _description = value;
            }
        }

        private string _description { get; set; }

        public List<DbColumnInfo> TableInfo { get; set; }

        public IEnumerable<DbColumnInfo> GetColumns(IEnumerable<string> names)
        {
            foreach (var name in names)
            {
                yield return GetColumn(name);
            }
        }
        public DbColumnInfo GetColumn(string name)
        {
            var column = TableInfo?.FirstOrDefault(c => c.Name.Equals(name,StringComparison.OrdinalIgnoreCase));
            //if (column == null)
            //{
            //    throw new ArgumentException("column not found", name);
            //}
            return column;
        }

        public bool ExistsColumn(string name)
        {
            return TableInfo?.Exists(c => c.Name.Equals(name, StringComparison.OrdinalIgnoreCase))== true;
        }
        /// <summary>
        /// 获取所有主键
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public IEnumerable<DbColumnInfo> GetKeyColumns()
        {
            return TableInfo?.Where(x => x.IsPrimaryKey);
        }

    }
}
